<?php

/**
 * IndexController
 * Carries several page behavior including view, list, edit, add and delete 
 * @author samuel
 *
 */

class IndexController extends Zend_Controller_Action
{
    /**
     * Initializes the page controller
     */
    
    public function init()
    
    {
        // Initialize the page DbTable object to make accessible in all the actions
        // in the controller
        $this->page  = new Application_Model_DbTable_Page();
    }

    /**
     * Gets data from form posts, compares it with table columns and returns
     * an array
     * @return array $data
     * 
     */
    private function _getData()
    {
        $tableCols = $this->page->info('cols');
        $posts = $this->_request->getPost();
        foreach($posts as $key => $post) {
            if(in_array($key, $tableCols)) {
                $data[$key] = $post;
            }
        }
        return $data;
    }

    /**
     * Views a page for a given id
     */
    public function indexAction()
    {
        // action body
        $id = $this->_request->getParam('id');
        $page = $this->page->fetchRow('pag_id = '.$id);
        $this->view->page = $page->toArray();
    }

    /**
     * AddAction
     */
    public function addAction()
    {
        if($this->_request->isPost()) {
            $row = $this->page->createRow($this->_getData());
            $row->ctg_id = 2;
            $row->created_by = 2;
            $row->created_on = date("Y-m-d",time());
            $row->save();
            $this->_redirect('index/list');
            //Zend_Debug::dump($tableCols, $label=null, $echo=true);exit;
            //Zend_Debug::dump($data, $label=null, $echo=true);exit;
        } else {
            $form = new Application_Form_Page();
            $this->view->form = $form;
        }
    }

    /**
     * editAction
     */
    public function editAction()
    {
        // action body
        $id = $this->_request->getParam('id');
        $row = $this->page->fetchRow('pag_id = '.$id);
        if($this->_request->isPost()) {
            $row->setFromArray($this->_getData());
            $row->modified_by = 2;
            $row->modified_on = date("Y-m-d",time());
            $row->save();
            $this->_redirect('index/list');
        } else {
            $form = new Application_Form_Page();
            $form->populate($row->toArray());
            $this->view->form = $form;
        }
        //Zend_Debug::Dump($row, $lable=false,$echo=true);
    }

    /**
     * listAction
     */
    public function listAction()
    {
        $pages = $this->page->fetchAll()->toArray();
        //Zend_Debug::Dump($pages, $lable=false,$echo=true);
        $this->view->pages = $pages;
    }
}







